package com.dot.base.wait01;

public class Thread04 {
    /**
     * 共享对象Res
     */
    class Res {
        public String userName;
        public char sex;
        public boolean flag = false;
    }

    class InputThread extends Thread {
        private Res res;

        public InputThread(Res res) {
            this.res = res;
        }

        @Override
        public void run() {
            int count = 0;
            while (true) {
                synchronized (res) {
                    if (res.flag == true) {
                        try {
                            res.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (count == 0) {
                        res.userName = "李小龙";
                        res.sex = '男';
                    } else {
                        res.userName = "小薇";
                        res.sex = '女';
                    }
                    count = (count + 1) % 2;
                    res.flag = true;
                    res.notify();
                }
            }
        }
    }

    class OutputThread extends Thread {
        private Res res;

        public OutputThread(Res res) {
            this.res = res;
        }

        @Override
        public void run() {

            while (true) {
                synchronized (res) {
                    if (!res.flag) {
                        try {
                            res.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(res.userName + "," + res.sex);
                    res.flag = false;
                    res.notify();
                }
            }
        }
    }

    public void print() {
        Res res = new Res();
        InputThread inputThread = new InputThread(res);
        OutputThread outputThread = new OutputThread(res);
        inputThread.start();
        outputThread.start();
    }

    public static void main(String[] args) {
        new Thread04().print();
    }
}
